package com.camel.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.camel.controller.utils.R;
import com.camel.domain.Book;
import com.camel.service.IBookService;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/books")
public class BookController{

    @Autowired
    private IBookService bookService;

    @GetMapping
    @ApiOperation(value = "通过主键查询单条数据",httpMethod = "GET")
    public R getAll() throws Exception{
        return new R(0,bookService.list());
    }
    @PostMapping
    public R save(@RequestBody Book book) throws Exception{
        boolean b = bookService.save(book);
        //判断是否添加成功，返回结果不同
        return new R(0,b?"添加成功^_^":"添加失败-_-!");
    }
    @PutMapping
    public R update(@RequestBody Book book) throws Exception{
        boolean b = bookService.updateById(book);
        //判断是否编辑成功，返回结果不同
        return new R(0,b?"编辑成功^_^":"数据同步失败，自动刷新");
    }
    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id) throws Exception{
        boolean b = bookService.removeById(id);
        //判断是否删除成功，返回结果不同
        return new R(0,b?"删除成功^_^":"数据同步失败，自动刷新");
    }
    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) throws Exception{
        return new R(0,bookService.getById(id));
    }
    @GetMapping("/{current}/{size}")
    public R getAll(@PathVariable Integer current,@PathVariable Integer size,Book book) throws Exception{
        IPage<Book> page = bookService.getPage(current,size,book);
        //如果当前页码值大于总页码值，那么重新执行查询操作，使用最大页码值作为当前页码值查询
        if(current>page.getPages())
        {
             page= bookService.getPage((int) page.getPages(),size,book);
        }
        return new R(0,page);
    }
}
